﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using CrawlerApp.Services;
using CrawlerApp.Services.Interfaces;
using CrawlerApp.Services.Job;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using CrawlerApp.Services.Interfaces.Job;
using CrawlerApp.Services.Interceptors;
using CrawlerApp.Services.Interceptors.Events;
using System.Reflection;
using CrawlerApp.Infrastructure.Interfaces;
using CrawlerApp.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;
using CrawlerApp.Infrastructure.Data;

namespace CrawlerApp.Configuration
{
    public static class ConfigureAppServices
    {
        public static App AddAppServices(this App app, ContainerBuilder builder)
        {
            builder.RegisterType<HtmlParseService>().As<IHtmlPraseService>().InstancePerDependency();

            // JobService
            //builder.RegisterType<CategoryJob>().As<IJob>().InstancePerDependency();
            //builder.RegisterType<TagJob>().As<IJob>().InstancePerDependency();
            builder.RegisterType<BookJob>().As<IJob>().InstancePerDependency();

            builder.RegisterType<StdSchedulerFactory>().As<ISchedulerFactory>().SingleInstance();
            builder.RegisterType<JobFactory>().As<IJobFactory>().SingleInstance();
            builder.RegisterType<JobService>().As<IJobService>().SingleInstance();

            // Interceptor AOP
            builder.RegisterType<DbContextInterceptor>().AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(typeof(App).GetTypeInfo().Assembly)
                .Where(type =>
                (typeof(IBookRepository).IsAssignableFrom(type) || typeof(IRepository<>).IsAssignableFrom(type)) &&
                type.IsPublic && !type.IsAbstract)
                    .AsImplementedInterfaces()
                    .InstancePerLifetimeScope()
                    .EnableInterfaceInterceptors()
                    .InterceptedBy(typeof(DbContextInterceptor));
            //builder.RegisterType<Interceptor<InterceptorEventHandler>>();
            //var assembly = typeof(App).GetTypeInfo().Assembly;
            //builder.RegisterAssemblyTypes(assembly)
            //    .Where(type =>
            //    (typeof(IBookRepository).IsAssignableFrom(type) || typeof(IRepository<>).IsAssignableFrom(type)) &&
            //    type.IsPublic &&
            //    !type.IsAbstract)
            //        .AsImplementedInterfaces()
            //        .InstancePerLifetimeScope()
            //        .EnableInterfaceInterceptors()
            //        .InterceptedBy(typeof(Interceptor<InterceptorEventHandler>));

            return app;
        }
    }
}
